package com.franklin.ideaplugin.easytesting.rpc;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.franklin.ideaplugin.easytesting.common.entity.ETRsp;
import com.franklin.ideaplugin.easytesting.entity.ExecuteResult;
import com.franklin.ideaplugin.easytesting.rpc.entity.HeartBeatData;
import com.franklin.ideaplugin.easytesting.rpc.entity.MethodInvokeData;
import okhttp3.*;

import java.awt.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author Ye Junhui
 * @since 2023/5/15
 */
public class RpcClient {

    private final static OkHttpClient okHttpClient = new okhttp3.OkHttpClient.Builder()
            .connectTimeout(90, TimeUnit.SECONDS)
            .writeTimeout(90,TimeUnit.SECONDS)
            .readTimeout(90,TimeUnit.SECONDS)
            .build();

    private static final MediaType APPLICATION_JSON = MediaType.parse("application/json; charset=utf-8");

    /**
     * 发送
     * @param executeResult
     * @param methodInvokeData
     * @param port
     * @param executeResultHandler
     */
    public static void sendExecuteBlock(
            ExecuteResult executeResult,
            MethodInvokeData methodInvokeData,
            String port,
            IExecuteResultHandler<ExecuteResult> executeResultHandler
    ) throws IOException {
        if (StrUtil.isBlank(port)) {
            return;
        }


        RequestBody requestBody = RequestBody.create(APPLICATION_JSON, JSON.toJSONString(methodInvokeData));
        final Request request = new Request.Builder()
                .url("http://127.0.0.1" + ":" + port + ServerPath.EXECUTE)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String serverResponse = response.body().string();
                if (StrUtil.isBlank(serverResponse)) {
                    return;
                }
                ETRsp etRsp = JSON.parseObject(serverResponse, ETRsp.class);
                executeResult.setEtRsp(etRsp);
                EventQueue.invokeLater(() -> {
                    if (methodInvokeData.isDownload()){
                        try {
                            Desktop.getDesktop().open(FileUtil.file(methodInvokeData.getDownloadPath()));
                        } catch (IOException e) {

                        }
                    }
                    executeResultHandler.handleResult(executeResult);
                });
            }
        });

    }

    /**
     * 发送
     * @param body
     * @param port
     * @param executeResultHandler
     */
    public static void sendExecuteBlock(
            String body,
            String port,
            IExecuteResultHandler<ETRsp<?>> executeResultHandler
    ) throws IOException {
        if (StrUtil.isBlank(port)) {
            return;
        }


        RequestBody requestBody = RequestBody.create(APPLICATION_JSON, body);
        final Request request = new Request.Builder()
                .url("http://127.0.0.1" + ":" + port + ServerPath.EXECUTE)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);

        Response response = call.execute();

        String serverResponse = response.body().string();
        if (StrUtil.isBlank(serverResponse)) {
            return;
        }
        ETRsp etRsp = JSON.parseObject(serverResponse, ETRsp.class);
        executeResultHandler.handleResult(etRsp);

    }


    /**
     * 发送心跳
     *
     * @param port
     * @return
     */
    public static boolean sendHeartBeat(String port) {
        if (StrUtil.isBlank(port)) {
            return false;
        }
        HeartBeatData heartBeatData = new HeartBeatData();
        RequestBody requestBody = RequestBody.create(APPLICATION_JSON, JSON.toJSONString(heartBeatData));
        ;
        final Request request = new Request.Builder()
                .url("http://127.0.0.1" + ":" + port + ServerPath.HEART_BEAT)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            call.execute();
            return true;
        } catch (IOException e) {
            return false;
        }
    }
}
